#include <regx52.h>
#include "intrins.h"
#include "delay.h"

sbit DIN  = P3^4;
sbit CS   = P3^5;
sbit CLK  = P3^6;
sbit DOUT = P3^7;

unsigned int read_2046(unsigned char ch) 
{
	unsigned char i = 0;
	unsigned char dat = 0xA7;//1 010   0   1  11  GR
	unsigned int  value = 0;
	
	if(ch == 1) //NTC
	{
		dat = 0xD7;//1 101   0   1  11
	} else if(ch == 2)//Res
	 {
		 dat = 0x97;//1 001   0   1  11
	 }else if(ch == 3)//TEMP1
	 {
		 dat = 0xF7;//1 111   0   1  11
	 }
	CS = 0;  _nop_();
	CLK = 0; _nop_();
	for(; i<8; ++i) 
	{
		if(dat & 0x80) 
		{
			DIN = 1;
		} else 
		{
			DIN = 0;
		}
		dat <<= 1;
		_nop_();
		CLK = 1;
		_nop_();
		CLK = 0;
	}
	DIN = 0;
	delay(2); //20us
	
	CLK = 1;
	_nop_();
	CLK = 0;
	_nop_();
	
	for(i=0; i<11; ++i) 
	{
		value <<= 1;
		value |= DOUT;
		CLK = 1;
		_nop_();
		CLK = 0;
		_nop_();
	}
	_nop_();
	CS = 1; 
	_nop_();
	return value;
}